package com.caineng.zhaobiao.zbapi.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.caineng.zhaobiao.zbapi.controller.paramVo.CaiBaseUserKeywordVo;
import com.caineng.zhaobiao.zbapi.dao.CaiBaseUserKeywordDao;
import com.caineng.zhaobiao.zbapi.domain.CaiBaseUserKeyword;
import com.caineng.zhaobiao.zbapi.service.CaiBaseUserKeywordService;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.mongodb.client.result.DeleteResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 订阅关键字和监控企业名单
 * @author liandyao
 * @date 2022/7/23 10:23
 */
@Slf4j
@Api(tags = "订阅关键字和监控企业名单")
@RestController
@RequestMapping("/zbapi/keyword")
public class CaiBaseUserKeywordController {

    @Autowired
    private CaiBaseUserKeywordDao keywordDao ;

    @Autowired
    private CaiBaseUserKeywordService keywordService ;

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/findAllByUserId")
    @ApiOperation(value = "查询当前用户订阅的关键字和监控的企业名单")
    public AjaxResult findAllByUserId(){
        //登录用户
        String userId = StpUtil.getLoginIdAsString();
        CaiBaseUserKeyword keyword = keywordService.getByUserId(userId);
        return AjaxResult.success("成功",keyword);

    }

    @PostMapping("/save")
    @ApiOperation(value = "保存当前用户订阅的关键字和监控的企业名单,前台需要传递json格式的数组形式" )
    public AjaxResult save(@RequestBody  CaiBaseUserKeywordVo keyword){
        log.info(JSONUtil.toJsonStr(keyword));

        //登录用户
        String userId = StpUtil.getLoginIdAsString();
        //先删除

        DeleteResult de = mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId)), CaiBaseUserKeyword.class);
        log.info(de.getDeletedCount()+"条记录被删除");
        //删除完成

        CaiBaseUserKeyword po = new CaiBaseUserKeyword();
        po.setUserId(userId);
        po.setKeyWord(keyword.getKeywords());
        po.setAreaName(keyword.getCitys());
        po.setListenCompany(keyword.getCompanys());
        po.setUpdateDate(new Date());
        keywordDao.save(po) ;

        return AjaxResult.success("成功");

    }


}
